package com.cloud.viewpostdemo.utils

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.buffer
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch

/**
 * @author: njb
 * @date:   2025/1/11 17:47
 * @desc:   描述
 */
class FlowDebounceUtil {
    companion object {

        // 防抖相关逻辑，返回经过防抖处理后的Flow
        fun <T> debounceFlow(sourceFlow: Flow<T>, debounceTime: Long, coroutineScope: CoroutineScope): Flow<T> {
            return sourceFlow.debounce(debounceTime).flowOn(coroutineScope.coroutineContext)
        }

        // 实现可动态设置先到达先处理的个数，之后的为后到后处理的逻辑，返回处理后的Flow
        fun <T> customProcessFlow(sourceFlow: Flow<T>, coroutineScope: CoroutineScope, firstProcessCount: Int): Flow<T> {
            val processedCount = mutableListOf<T>()
            var count = 0
            val sharedFlow = MutableSharedFlow<T>()
            sourceFlow.buffer().onEach {
                count++
                processedCount.add(it)
                if (count <= firstProcessCount) {
                    sharedFlow.tryEmit(processedCount.removeFirst())
                } else {
                    // 模拟后到后处理的延迟等情况，这里简单延迟300毫秒，可根据实际调整
                    coroutineScope.launch {
                        delay(300)
                        sharedFlow.tryEmit(processedCount.removeFirst())
                    }
                }
            }.launchIn(coroutineScope)
            return sharedFlow
        }
    }
}